<?php

namespace App\Http\Resources\Train;


use App\Facades\Plane\PlaneCitySeedFacade;
use App\Models\Plane\Airports\Repositories\Interfaces\AirportRepositoryInterface;
use App\Trip\Orders\TripType;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class HistorySource extends JsonResource
{
    /**
     * Transform the resource collection into an array.
     *
     * @param Request $request
     * @return array
     */

    public function toArray($request)
    {
        $history = parent::toArray($request);
        $only    = [
            'trip_type',
            'from_type',
            'from_code',
            'to_type',
            'to_code',
            'from_name',
            'from_name_uy',
            'to_name',
            'to_name_uy',
        ];

        if ($history['trip_type'] == TripType::TRIP_TYPE_PLANE) {
            $airportRepo = app(AirportRepositoryInterface::class);
            if ($history['from_type'] == 0) {
                $history['from_name']        = PlaneCitySeedFacade::getCityNameByCode($history['from_code']);
                $history['from_name_uy']     = PlaneCitySeedFacade::getCityNameUyByCode($history['from_code']);
                $history['from_city_adcode'] = PlaneCitySeedFacade::getCityAdcodeByCode($history['from_code']);

            } else if ($history['from_type'] == 2) {
                $airport                     = $airportRepo->findOneByCode($history['from_code']);
                $history['from_city_adcode'] = $airport?->getPlaneCityCode() ? PlaneCitySeedFacade::getCityAdcodeByCode($airport->getPlaneCityCode()) : '';
            }

            if ($history['to_type'] == 0) {
                $history['to_name']        = PlaneCitySeedFacade::getCityNameByCode($history['to_code']);
                $history['to_name_uy']     = PlaneCitySeedFacade::getCityNameUyByCode($history['to_code']);
                $history['to_city_adcode'] = PlaneCitySeedFacade::getCityAdcodeByCode($history['to_code']);
            } else if ($history['to_type'] == 2) {
                $airport                   = $airportRepo->findOneByCode($history['to_code']);
                $history['to_city_adcode'] = $airport?->getPlaneCityCode() ? PlaneCitySeedFacade::getCityAdcodeByCode($airport->getPlaneCityCode()) : '';
            }

            array_push($only, 'from_city_adcode', 'to_city_adcode');
        }

        return collect($history)
            ->only($only)->toArray();

    }
}
